package com.zmn.oms.zmn.business.impl.open.v2;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.http.HttpUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.consts.GlobalConsts;
import com.zmn.oms.business.interfaces.remark.OrderRemarkBService;
import com.zmn.oms.common.constant.OpenApiConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderDutyConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.model.dto.open.v2.*;
import com.zmn.oms.model.entity.chan.plat.ChannelInterface;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.master.OrderMaster;
import com.zmn.oms.model.entity.order.OrderExtend;
import com.zmn.oms.model.entity.orderattachment.OrderAttachment;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.remark.OrderRemark;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkLogChange;
import com.zmn.oms.model.vo.remark.OrderRemarkDetailVO;
import com.zmn.oms.model.vo.remark.OrderRemarkVO;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.master.OrderMasterService;
import com.zmn.oms.services.interfaces.order.OrderExtendService;
import com.zmn.oms.services.interfaces.orderattachment.OrderAttachmentService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.oms.services.interfaces.remark.OrderRemarkService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.third.base.util.MasterPhoneUtil;
import com.zmn.oms.zmn.business.interfaces.chan.ChannelInterfaceBService;
import com.zmn.oms.zmn.business.interfaces.open.v2.V2OrderStatusSyncService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 类描述：第2版同步订单信息实现类
 *
 * @author LiangHailong
 * @date 2019/12/23 18:43
 */
@Slf4j
@Service("v2OrderStatusSyncService")
public class V2OrderStatusSyncServiceImpl implements V2OrderStatusSyncService {
    private static final String API_VERSION = "2";
    private static final  String FIELD_EXTRADATA = "extraData";

    @Autowired
    private OrderMasterService orderMasterService;
    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderProductService orderProductService;
    @Autowired
    private OrderRemarkBService orderRemarkBService;
    @Autowired
    private OrderExtendService orderExtendService;
    @Autowired
    private OrderAttachmentService orderAttachmentService;
    @Autowired
    private OrderRemarkService orderRemarkService;
    @Autowired
    private ChannelInterfaceBService channelInterfaceBService;

    /**
     * 推送新单
     * @param orderWorkLogChange
     * @return
     */
    @Override
    public ResultDTO pushNewOrder(OrderWorkLogChange orderWorkLogChange) {
        ChannelInterface channelInterface = getChannelInterface(orderWorkLogChange.getChannelId());
        if (channelInterface == null || StringUtils.isBlank(channelInterface.getInterfaceUrl())) {
            return null;
        }

        Long orderId = orderWorkLogChange.getOrderId();
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);
        OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);
        List<OrderProduct> orderProducts = orderProductService.listOrderProductByOrderId(orderId);

        PushNewOrderDTO jsonData = getPushNewOrderDTO(orderWork, orderDetail, orderProducts);

        Map<String, String> params = newRequestParams(channelInterface.getChannelId(),
                channelInterface.getAppSecret(), OpenApiConsts.FUNID_NEW_ORDER, jsonData, API_VERSION);

        log.info("[OpenAPI-V2-pushNewOrder-request] orderId=[{}], url=[{}], data=[{}]",
                orderId, channelInterface.getInterfaceUrl(), JSON.toJSONString(params));
        String response = HttpUtil.post(channelInterface.getInterfaceUrl(), params);
        log.info("[OpenAPI-V2-pushNewOrder-response] orderId=[{}], response=[{}]", orderId, response);

        return toResultDTO(orderWorkLogChange, OpenApiConsts.NOTIFY_STATUS_INPUT, response, OrderConsts.ORDER_NOTIFY_TYPE_NEW);
    }

    /**
     * 推送预约时间
     * @param orderWorkLogChange
     * @return
     */
    @Override
    public ResultDTO pushDutyTime(OrderWorkLogChange orderWorkLogChange) {
        Long orderId = orderWorkLogChange.getOrderId();
        Date dutyTime = orderWorkLogChange.getDutyTime();
        if (dutyTime == null) {
            return null;
        }

        ChannelInterface channelInterface = getChannelInterface(orderWorkLogChange.getChannelId());
        if (channelInterface == null || StringUtils.isBlank(channelInterface.getInterfaceStatusUrl())) {
            return null;
        }

        PushDutyTimeDTO jsonData = BeanMapper.map(this.buildPushOrderDTO(orderWorkLogChange),PushDutyTimeDTO.class);
        jsonData.setDutyTime(dutyTime.getTime()/1000);

        Map<String, String> params = newRequestParams(channelInterface.getChannelId(),
                channelInterface.getAppSecret(), OpenApiConsts.FUNID_DUTY_TIME, jsonData, API_VERSION);

        log.info("[OpenAPI-V2-pushDutyTime-request] orderId=[{}], url=[{}], data=[{}]",
                orderId, channelInterface.getInterfaceStatusUrl(), JSON.toJSONString(params));
        String response = HttpUtil.post(channelInterface.getInterfaceStatusUrl(), params);
        log.info("[OpenAPI-V2-pushDutyTime-response] orderId=[{}], response=[{}]", orderId, response);

        return toResultDTO(orderWorkLogChange, OpenApiConsts.NOTIFY_STATUS_CONFIRM, response);
    }

    /**
     * 推送派单工程师
     * @param orderWorkLogChange
     * @return
     */
    @Override
    public ResultDTO pushMasterInfo(OrderWorkLogChange orderWorkLogChange) {

        ChannelInterface channelInterface = getChannelInterface(orderWorkLogChange.getChannelId());
        if (channelInterface == null || StringUtils.isBlank(channelInterface.getInterfaceStatusUrl())) {
            return null;
        }

        Long orderId = orderWorkLogChange.getOrderId();
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);

        // 领单工程师
        Integer masterId = orderWork.getMasterId();
        OrderMaster master = findOrderMaster(orderId, masterId);
        if (master == null) {
            return null;
        }

        PushMasterInfoDTO jsonData = BeanMapper.map(this.buildPushOrderDTO(orderWorkLogChange),PushMasterInfoDTO.class);
        jsonData.setMasterName(
                Optional.ofNullable(master.getMasterName())
                        .filter(name -> name.length() >= 1)
                        .map(name -> String.format("%s工程师", name.substring(0,1)))
                        .orElse("工程师")
        );
        jsonData.setMasterPhone(
                Optional.ofNullable(orderDetailService.findOrderDetailByKey(orderId))
                        .map(orderDetail -> {
                            if (Objects.equals(orderDetail.getBindStatus(), OrderConsts.BIND_STATUS_BIND)
                                    && StringUtils.isNotBlank(orderDetail.getBindTelephone())) {
                                return orderDetail.getBindTelephone();
                            }
                            return null;
                        })
                        .orElse(MasterPhoneUtil.getSafeMasterPhone(orderWork.getCityId()))
        );

        Map<String, String> params = newRequestParams(channelInterface.getChannelId(),
                channelInterface.getAppSecret(), OpenApiConsts.FUNID_MASTER_INFO, jsonData, API_VERSION);

        log.info("[OpenAPI-V2-pushMasterInfo-request] orderId=[{}], url=[{}], data=[{}]",
                orderId, channelInterface.getInterfaceStatusUrl(), JSON.toJSONString(params));
        String response = HttpUtil.post(channelInterface.getInterfaceStatusUrl(), params);
        log.info("[OpenAPI-V2-pushMasterInfo-response] orderId=[{}], response=[{}]", orderId, response);

        return toResultDTO(orderWorkLogChange, OpenApiConsts.NOTIFY_STATUS_DISTRIBUTE, response);
    }

    /**
     * 推送工程师上门
     * @param orderWorkLogChange
     * @return
     */
    @Override
    public ResultDTO pushMasterVisit(OrderWorkLogChange orderWorkLogChange) {
        Long orderId = orderWorkLogChange.getOrderId();

        ChannelInterface channelInterface = getChannelInterface(orderWorkLogChange.getChannelId());
        if (channelInterface == null || StringUtils.isBlank(channelInterface.getInterfaceStatusUrl())) {
            return null;
        }

        PushOrderDTO jsonData = this.buildPushOrderDTO(orderWorkLogChange);

        Map<String, String> params = newRequestParams(channelInterface.getChannelId(),
                channelInterface.getAppSecret(), OpenApiConsts.FUNID_MASTER_VISIT, jsonData, API_VERSION);

        log.info("[OpenAPI-V2-pushMasterVisit-request] orderId=[{}], url=[{}], data=[{}]",
                orderId, channelInterface.getInterfaceStatusUrl(), JSON.toJSONString(params));
        String response = HttpUtil.post(channelInterface.getInterfaceStatusUrl(), params);
        log.info("[OpenAPI-V2-pushMasterVisit-response] orderId=[{}], response=[{}]", orderId, response);

        return toResultDTO(orderWorkLogChange, OpenApiConsts.NOTIFY_STATUS_VISIT, response);
    }

    /**
     * 推送订单状态为挂起
     * @param orderWorkLogChange
     * @return
     */
    @Override
    public ResultDTO pushOrderSuspend(OrderWorkLogChange orderWorkLogChange) {
        Long orderId = orderWorkLogChange.getOrderId();
        Long workId = orderWorkLogChange.getWorkId();

        // 暂时只对厂商单同步
        if (!Objects.equals(orderWorkLogChange.getOrderSourceType(),OrderConsts.ORDER_SOURCE_TYPE_FACTORY)) {
            return null;
        }

        ChannelInterface channelInterface = getChannelInterface(orderWorkLogChange.getChannelId());
        if (channelInterface == null || StringUtils.isBlank(channelInterface.getInterfaceStatusUrl())) {
            return null;
        }

        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId,workId);
        if (Objects.isNull(orderWork)) {
            log.info("[OpenAPI-V2-pushOrderSuspend] find OrderWork failed,orderId=[{}]",orderId);
            return null;
        }

        if (!Objects.equals(orderWork.getDutyStatus(), OrderDutyConsts.DUTY_STATUS_SUSPEND)) {
            log.info("[OpenAPI-V2-pushOrderSuspend] OrderWork duty status isn't suspend,orderId=[{}],dutyStatus=[{}]",orderId,orderWork.getDutyStatus());
            return null;
        }

        // 挂起原因
        StringBuilder sbReason = new StringBuilder();
        sbReason.append(OrderDutyConsts.getDutySuspendReasonName(orderWork.getDutyFailCode()));
        OrderRemark orderRemark = orderRemarkService.findByOrderIdAndType(orderId, workId, OrderConsts.ORDER_REMARK_TYPE_SUSPEND);
        if (Objects.nonNull(orderRemark)) {
            sbReason.append(orderRemark.getContent());
        }

        // 同步数据
        PushOrderSuspendDTO jsonData = BeanMapper.map(this.buildPushOrderDTO(orderWorkLogChange),PushOrderSuspendDTO.class);
        jsonData.setSuspendReason(sbReason.toString());
        jsonData.setNextContactTime(DateUtil.toTimestamp(orderWork.getNextContactTime()));

        Map<String, String> params = newRequestParams(channelInterface.getChannelId(),
                channelInterface.getAppSecret(), OpenApiConsts.FUNID_ORDER_SUSPEND, jsonData, API_VERSION);

        log.info("[OpenAPI-V2-pushOrderSuspend-request] orderId=[{}], url=[{}], data=[{}]",
                orderId, channelInterface.getInterfaceStatusUrl(), JSON.toJSONString(params));
        String response = HttpUtil.post(channelInterface.getInterfaceStatusUrl(), params);
        log.info("[OpenAPI-V2-pushOrderSuspend-response] orderId=[{}], response=[{}]", orderId, response);

        return toResultDTO(orderWorkLogChange, OpenApiConsts.NOTIFY_STATUS_SUSPEND, response);
    }

    /**
     * 推送订单服务完成
     * @param orderWorkLogChange
     * @return
     */
    @Override
    public ResultDTO pushServiceComplete(OrderWorkLogChange orderWorkLogChange) {
        ChannelInterface channelInterface = getChannelInterface(orderWorkLogChange.getChannelId());
        if (channelInterface == null || StringUtils.isBlank(channelInterface.getInterfaceStatusUrl())) {
            return null;
        }

        Long orderId = orderWorkLogChange.getOrderId();
        PushServiceCompleteDTO pushServiceCompleteDTO = BeanMapper.map(this.buildPushOrderDTO(orderWorkLogChange),PushServiceCompleteDTO.class);

        // 扩展数据
        pushServiceCompleteDTO.setExtraData(this.getOrderExtraData(orderId));

        // 厂商订单，返回产品照片信息
        if (Objects.equals(OrderConsts.ORDER_SOURCE_TYPE_FACTORY, orderWorkLogChange.getOrderSourceType())) {
            pushServiceCompleteDTO.setProductPictureUrls(this.getOrderImageSrc(orderId));
        }

        // 生成参数
        Map<String, String> params = newRequestParams(channelInterface.getChannelId(),
                channelInterface.getAppSecret(), OpenApiConsts.FUNID_SERVICE_COMPLETE, pushServiceCompleteDTO, API_VERSION);

        log.info("[OpenAPI-V2-pushServiceComplete-request] orderId=[{}], url=[{}], data=[{}]",
                orderId, channelInterface.getInterfaceStatusUrl(), JSON.toJSONString(params));
        String response = HttpUtil.post(channelInterface.getInterfaceStatusUrl(), params);
        log.info("[OpenAPI-V2-pushServiceComplete-response] orderId=[{}], response=[{}]", orderId, response);

        return toResultDTO(orderWorkLogChange, OpenApiConsts.NOTIFY_STATUS_SERVICE_COMPLETE, response);
    }

    /**
     * 推送订单成功
     * @param orderWorkLogChange
     * @return
     */
    @Override
    public ResultDTO pushOrderComplete(OrderWorkLogChange orderWorkLogChange) {
        Long orderId = orderWorkLogChange.getOrderId();

        ChannelInterface channelInterface = getChannelInterface(orderWorkLogChange.getChannelId());
        if (channelInterface == null || StringUtils.isBlank(channelInterface.getInterfaceStatusUrl())) {
            return null;
        }

        PushOrderCompleteDTO jsonData = BeanMapper.map(this.buildPushOrderDTO(orderWorkLogChange),PushOrderCompleteDTO.class);

        // 扩展数据
        jsonData.setExtraData(this.getOrderExtraData(orderId));

        // 厂商订单，返回产品照片信息
        if (Objects.equals(OrderConsts.ORDER_SOURCE_TYPE_FACTORY, orderWorkLogChange.getOrderSourceType())) {
            jsonData.setProductPictureUrls(this.getOrderImageSrc(orderId));
        }

        Map<String, String> params = newRequestParams(channelInterface.getChannelId(),
                channelInterface.getAppSecret(), OpenApiConsts.FUNID_ORDER_COMPLETE, jsonData, API_VERSION);

        log.info("[OpenAPI-V2-pushOrderComplete-request] orderId=[{}], url=[{}], data=[{}]",
                orderId, channelInterface.getInterfaceStatusUrl(), JSON.toJSONString(params));
        String response = HttpUtil.post(channelInterface.getInterfaceStatusUrl(), params);
        log.info("[OpenAPI-V2-pushOrderComplete-response] orderId=[{}], response=[{}]", orderId, response);

        return toResultDTO(orderWorkLogChange, OpenApiConsts.NOTIFY_STATUS_COMPLETE, response);
    }

    /**
     * 推送订单取消
     * @param orderWorkLogChange
     * @return
     */
    @Override
    public ResultDTO pushOrderCancel(OrderWorkLogChange orderWorkLogChange) {
        Long orderId = orderWorkLogChange.getOrderId();

        ChannelInterface channelInterface = getChannelInterface(orderWorkLogChange.getChannelId());
        if (channelInterface == null || StringUtils.isBlank(channelInterface.getInterfaceStatusUrl())) {
            return null;
        }

        PushOrderDTO jsonData = this.buildPushOrderDTO(orderWorkLogChange);

        // 取消备注（原因），需要将手写备注和选项备注进行拼接
        OrderRemarkVO orderRemarkVO = orderRemarkBService.findOrderRemarkVO(orderId, orderId,
                OrderConsts.ORDER_REMARK_TYPE_CANCEL);
        List<String> remarkList = new LinkedList<>();
        if (StringUtils.isNotBlank(orderRemarkVO.getContent())) {
            remarkList.add(orderRemarkVO.getContent());
        }
        if (orderRemarkVO.getDetailVOList() != null) {
            for (OrderRemarkDetailVO item : orderRemarkVO.getDetailVOList()) {
                remarkList.add(item.getMapName());
            }
        }
        String remark = (remarkList.size() > 0) ? StringUtils.join(remarkList, "，") : null;
        jsonData.setRemark(remark);

        Map<String, String> params = newRequestParams(channelInterface.getChannelId(),
                channelInterface.getAppSecret(), OpenApiConsts.FUNID_ORDER_CANCEL, jsonData, API_VERSION);

        log.info("[OpenAPI-V2-pushOrderCancel-request] orderId=[{}], url=[{}], data=[{}]",
                orderId, channelInterface.getInterfaceStatusUrl(), JSON.toJSONString(params));
        String response = HttpUtil.post(channelInterface.getInterfaceStatusUrl(), params);
        log.info("[OpenAPI-V2-pushOrderCancel-response] orderId=[{}], response=[{}]", orderId, response);

        return toResultDTO(orderWorkLogChange, OpenApiConsts.NOTIFY_STATUS_CANCEL, response);
    }

    /**
     * 推送商家备注信息（只针对厂商订单）
     * @param orderWorkLogChange
     * @return
     */
    @Override
    public ResultDTO pushFactoryRemark(OrderWorkLogChange orderWorkLogChange) {
        Long orderId = orderWorkLogChange.getOrderId();
        String factoryRemark = orderWorkLogChange.getExtData();
        if (StringUtils.isBlank(factoryRemark)) {
            return null;
        }

        ChannelInterface channelInterface = getChannelInterface(orderWorkLogChange.getChannelId());
        if (channelInterface == null || StringUtils.isBlank(channelInterface.getInterfaceStatusUrl())) {
            return null;
        }

        PushOrderDTO jsonData = this.buildPushOrderDTO(orderWorkLogChange);

        jsonData.setRemark(factoryRemark);

        Map<String, String> params = newRequestParams(channelInterface.getChannelId(),
                channelInterface.getAppSecret(), OpenApiConsts.FUNID_FACTORY_REMARK, jsonData, API_VERSION);

        log.info("[OpenAPI-V2-pushFactoryRemark-request] orderId=[{}], url=[{}], data=[{}]",
                orderId, channelInterface.getInterfaceStatusUrl(), JSON.toJSONString(params));
        String response = HttpUtil.post(channelInterface.getInterfaceStatusUrl(), params);
        log.info("[OpenAPI-V2-pushFactoryRemark-response] orderId=[{}], response=[{}]", orderId, response);

        return toResultDTO(orderWorkLogChange, OpenApiConsts.NOTIFY_STATUS_FACTORY_REMARK, response);
    }

    /**
     * 获取渠道接入数据
     * @param channelId
     * @return
     */
    private ChannelInterface getChannelInterface(Integer channelId) {
        Optional<ChannelInterface> optional = channelInterfaceBService.findByChannelId(channelId);
        if (!optional.isPresent()) {
            return null;
        }

        ChannelInterface channelInterface = optional.get();
        if (channelInterface.getStatus() != null && !Objects.equals(GlobalConsts.YES, channelInterface.getStatus())) {
            return null;
        }

        return channelInterface;
    }

    /**
     * 查询领单工程师信息
     * @param orderId
     * @param masterId
     */
    private OrderMaster findOrderMaster(Long orderId, Integer masterId) {
        List<OrderMaster> masterList = orderMasterService.listMasterByWorkId(orderId, orderId);
        if (masterList == null) {
            return null;
        }

        for (OrderMaster item : masterList) {
            if (item.getMasterId().equals(masterId)) {
                return item;
            }
        }

        return null;
    }

    /**
     * 封装推送新单数据
     * @param orderWork
     * @param orderProducts
     * @return
     */
    private PushNewOrderDTO getPushNewOrderDTO(OrderWork orderWork, OrderDetail orderDetail,
                                               List<OrderProduct> orderProducts) {

        PushNewOrderDTO pushNewOrderDTO = new PushNewOrderDTO();

        // orderWork
        pushNewOrderDTO.setOrderId(String.valueOf(orderWork.getOrderId()));
        pushNewOrderDTO.setThirdOrderId(orderWork.getOuterId());
        pushNewOrderDTO.setOptTime(DateUtil.getNowTimestamp());
        pushNewOrderDTO.setCreateTime(String.valueOf(orderWork.getCreateTime().getTime()/1000));
        pushNewOrderDTO.setCityId(String.valueOf(orderWork.getCityId()));
        pushNewOrderDTO.setServiceType(orderWork.getServCategId());
        if (Objects.nonNull(orderWork.getDutyTime())) {
            pushNewOrderDTO.setCreateTime(String.valueOf(orderWork.getDutyTime().getTime()/1000));
        }

        // orderDetail
        pushNewOrderDTO.setUserName(orderDetail.getUserName());
        pushNewOrderDTO.setUserPhone(orderDetail.getTelephone());
        pushNewOrderDTO.setStreet(orderDetail.getStreet());
        pushNewOrderDTO.setAddress(orderDetail.getAddress());
        pushNewOrderDTO.setLatitude(String.valueOf(orderDetail.getLatitude()));
        pushNewOrderDTO.setLongitude(String.valueOf(orderDetail.getLongitude()));
        // orderProduct
        List<PushNewOrderDTO.Product> products = new LinkedList();
        for (OrderProduct item : orderProducts) {
            PushNewOrderDTO.Product obj = new PushNewOrderDTO.Product();
            // TODO -lhl 后台产品ID为0怎么办？
            obj.setProductId(String.valueOf(item.getProductId()));
            obj.setProductName(item.getShowProductName());
            obj.setCount(item.getNumber());
            products.add(obj);
        }
        pushNewOrderDTO.setProducts(products);

        // ExtraData
        pushNewOrderDTO.setExtraData(this.getOrderExtraData(orderWork.getOrderId()));

        return pushNewOrderDTO;
    }

    /**
     * 生成PushOrderDTO对象
     * @return
     */
    protected PushOrderDTO buildPushOrderDTO(OrderWorkLogChange orderWorkLogChange) {

        if (Objects.isNull(orderWorkLogChange)) {
            return null;
        }

        PushOrderDTO pushOrderDTO = new PushOrderDTO();
        pushOrderDTO.setOrderId(String.valueOf(orderWorkLogChange.getOrderId()));
        pushOrderDTO.setThirdOrderId(orderWorkLogChange.getOuterId());

        Date optTime = Optional.ofNullable(orderWorkLogChange.getOpTime()).orElse(new Date());
        pushOrderDTO.setOptTime(optTime.getTime()/1000);

        return pushOrderDTO;
    }

    /**
     * 读取订单的扩展信息
     *
     * @param orderId
     * @return
     */
    protected String getOrderExtraData(Long orderId) {

        // 扩展信息
        OrderExtend orderExtend = orderExtendService.findOrderExtendByOrderId(orderId);
        if (Objects.isNull(orderExtend)) {
            return null;
        }

        // 合作方扩展数据
        if (StringUtils.isNotBlank(orderExtend.getExtraData())) {
            return orderExtend.getExtraData();
        }

        if (StringUtils.isNotBlank(orderExtend.getOuterData())) {
            JSONObject jsonObject = JSON.parseObject(orderExtend.getOuterData());
            if (jsonObject.containsKey(FIELD_EXTRADATA)) {
                return jsonObject.getString(FIELD_EXTRADATA);
            }
        }

        return null;
    }

    /**
     * 读取订单的图片url，用于服务完成，工单完成
     *
     * @param orderId
     * @return
     */
    protected String getOrderImageSrc(Long orderId) {

        String imageSrc = "";
        StringBuilder sbImageSrc = new StringBuilder();

        // 读取 oms_order_attachment 的工单照片
        List<OrderAttachment> orderAttachments = orderAttachmentService.listAttachmentByOrderId(orderId);
        if (!CollectionUtils.isEmpty(orderAttachments)) {

            for (OrderAttachment item : orderAttachments) {
                if (StringUtils.isBlank(item.getSrc())) {
                    continue;
                }

                String[] split = item.getSrc().split(",");
                for (String src : split) {
                    if (StringUtils.isNotBlank(src)) {
                        sbImageSrc.append(",").append(src);
                    }
                }
            }

            if (sbImageSrc.length() > 1) {
                imageSrc = sbImageSrc.substring(1);
            }
        }

        if (StringUtils.isNotBlank(imageSrc)) {
            return imageSrc;
        }

        // 扩展信息
        OrderExtend orderExtend = orderExtendService.findOrderExtendByOrderId(orderId);

        return Objects.isNull(orderExtend) ? null:orderExtend.getImageSrc();
    }

    /*============================================*/
    /*=================== main ===================*/
    /*============================================*/
    public static void main(String[] args) {
        Integer appId = 31050;
        String secretkey = "08afb419a01742dc9a4c42825e584b3b";
        String pushUrl = "https://sf.dsmxp.com/sale/api/order/yeyx/updateStatus";

        V2OrderStatusSyncServiceImpl service = new V2OrderStatusSyncServiceImpl();
        service.testPushComplete(appId, secretkey, pushUrl);
    }

    // 推送新单测试
    public void testPushNewOrder(Integer appId, String secretkey, String pushUrl) {
        PushNewOrderDTO pushNewOrderDTO = new PushNewOrderDTO();
        // orderWork
        pushNewOrderDTO.setOrderId("418414590875938817");
        pushNewOrderDTO.setCreateTime(String.valueOf(System.currentTimeMillis()/1000));
        pushNewOrderDTO.setCityId(String.valueOf("110100"));
        pushNewOrderDTO.setServiceType(GlobalConsts.SERV_CATEG_REPAIR);
        // orderDetail
        pushNewOrderDTO.setUserName("李四");
        pushNewOrderDTO.setUserPhone("18012345678");
        pushNewOrderDTO.setStreet("朝阳区北土城西路7号");
        pushNewOrderDTO.setAddress("B座903");
        pushNewOrderDTO.setLatitude("39.983487");
        pushNewOrderDTO.setLongitude("116.392797");
        // orderProduct
        List<PushNewOrderDTO.Product> products = new LinkedList();
        PushNewOrderDTO.Product obj = new PushNewOrderDTO.Product();
        obj.setProductId("10010");
        obj.setProductName("挂机空调维修");
        obj.setCount(1);
        products.add(obj);
        pushNewOrderDTO.setProducts(products);

        Map<String, String> params = newRequestParams(appId, secretkey, OpenApiConsts.FUNID_NEW_ORDER,
                pushNewOrderDTO, API_VERSION);

        log.info("[OpenAPI-V2-pushNewOrder-request] orderId=[{}], url=[{}], data=[{}]",
                418414590875938816L, pushUrl, JSON.toJSONString(params));
        String response = HttpUtil.post(pushUrl, params);
        log.info("[OpenAPI-V2-pushNewOrder-response] orderId=[{}], response=[{}]", 418414590875938816L, response);
    }


    public void testPushComplete(Integer appId, String secretkey, String pushUrl) {
        PushOrderCompleteDTO jsonData = new PushOrderCompleteDTO();
        jsonData.setOrderId("491506179659276288");
        jsonData.setThirdOrderId("297626169603129344");
        jsonData.setOptTime(1595307675L);
        jsonData.setExtraData("127996004847");
        jsonData.setProductPictureUrls("https://img1.xiujiadian.com/prod/mapp/202007/20200721130021_724228.jpg,https://img1.xiujiadian.com/prod/mapp/202007/20200721130022_253526.jpg,https://img1.xiujiadian.com/prod/mapp/202007/20200721130023_842700.jpg");

        Map<String, String> params = newRequestParams(appId,
                secretkey, OpenApiConsts.FUNID_ORDER_COMPLETE, jsonData, API_VERSION);

        log.info("[OpenAPI-V2-pushOrderComplete-request] orderId=[{}], url=[{}], data=[{}]",
                "491506179659276288", pushUrl, JSON.toJSONString(params));
        String response = HttpUtil.post(pushUrl, params);
        log.info("[OpenAPI-V2-pushOrderComplete-response] orderId=[{}], response=[{}]", "491506179659276288", response);

    }
}
